<!--
author:        hejiyang <silentmanager@163.com>
date:          2024-11-24 11:35:04
component:     delivery
Copyright © YourCompanyName All rights reserved
物流发货
-->
<template>
  <el-dialog
    :destroy-on-close="true"
    title="订单发货"
    v-model="isVisible"
    @close="handleClose"
    width="600px"
  >
    <el-form :model="formData" ref="formRef" :rules="rules">
      <el-form-item label="物流类型" prop="logisticType">
        <el-select placeholder="请选择物流类型" v-model="formData.logisticType">
          <el-option label="特惠包裹" :value="1">特惠包裹</el-option>
          <el-option label="电商标快" :value="2">电商标快</el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessageBox, FormRules } from 'element-plus'
import { reactive } from 'vue'
import { ref, watch, defineProps, defineEmits } from 'vue'
import { batchDeliveringLogistics, mergeDeliveringLogistics } from '@/api/logistics'

// 定义组件的 props
interface Props {
  merge: boolean
  visible: boolean
  orderIds: number[]
}
const rules = reactive<FormRules>({
  logisticType: [{ required: true, message: '请选择发货方式', trigger: 'blur' }]
})

// 获取 props 和 emits
const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void // 添加 success 事件
}>()

// 局部状态变量，用于管理弹窗的可见性
const isVisible = ref<boolean>(props.visible)
const loading = ref(false)

// 关闭弹窗的处理函数
const handleClose = () => {
  isVisible.value = false // 设置局部状态
  emit('update:visible', false) // 通知父组件
  formData.value.logisticType = undefined
}
const formRef = ref()
const formData = ref({
  logisticType: undefined
})
// 保存备注的处理函数
const handleSave = async () => {
  loading.value = true
  try {
    await formRef.value?.validate()
    // 选择调用的发货函数
    const deliverFunction = props.merge ? mergeDeliveringLogistics : batchDeliveringLogistics;
    const res = await deliverFunction({
      orderIds: props.orderIds,
      logisticType: formData.value.logisticType as unknown as number
    });

    if (res.code === 0) {
      await ElMessageBox.alert(res.data,   {
        dangerouslyUseHTMLString: true,
        },

      )
      emit('success') // 通知父组件
      handleClose() // 保存后关闭弹窗
      loading.value = false
    }
  } catch (e) {
    loading.value = false
    console.error(e)
  }
}
watch(
  () => props.visible,
  (newValue) => {
    isVisible.value = newValue
  }
)
</script>
